// pages/afterservice/afterservice.js
Page({

  data: {
    // 物品信息
    itemid:"",
    orderid:"",
    pic:'',
    title:'',
    value:"",
    deposit:"",
    applymoney:'',
    // 选择原因
    //当前选中数组的下标值
    customIndex: [0, 0, 0],
    //当前选中数组
    onlyArray: [[],[],[]],
    //customArray假设为我们从后台获取到的json数据 
    customArray: [
      {
        name: '物品划痕',
        dept:[
          {name: '2mm到5mm',
            product: [
              {name: '押金2.00%'},
            ]},
          {name: '5mm到10mm',
            product: [
              {name: '押金5.00%'}
            ]},
          {name: '10mm到30mm',
            product: [
              {name: '押金10.00%'}
            ]},
            {name: '超过30mm',
              product: [
                {name: '押金15.00%'}
              ]
            }
        ]
      },
      {
          name: '物品破损',
          dept:[
            {name: '2mm到5mm',
              product: [
                {name: '押金5.00%'},
              ]},
            {name: '5mm到10mm',
              product: [
                {name: '押金8.00%'}
              ]},
            {name: '10mm到30mm',
              product: [
                {name: '押金15.00%'}
              ]},
              {name: '超过30mm',
                product: [
                  {name: '押金50.00%'}
                ]
              }
          ]
      },
      {
        name: '物品无法使用',
        dept:[
          {name: '无标准',
            product: [
              {name: '押金100.00%'},
              ]},
        ]
      },
    ],
    //申请图片
    showpic:'',
    judgetext:'',
    picurls:[],
    //是否有服务
    isservice:"",
    //最终结果
    finalresult:"",
    applystate:"提交申请"
  },
  onLoad(options){

    var that = this;
    this.setData({
      orderid:options.orderid,
      itemid:options.itemid
    })

    if(options.orderid && options.itemid){
        //物品信息渲染
        wx.request({
          url: 'http://127.0.0.1:8080/item/selectItemById',
          method:"POST",
          data:{itemid:options.itemid},
          success(res){
            // console.log(res)
            if(res.data){
              var data = res.data[0];
              data.itemPic = JSON.parse(data.itemPic)
              that.setData({
                // 物品信息
                pic:data.itemPic[0],
                title:data.itemTitle,
                value:data.dayRent,
                deposit:data.deposit,
              })
            }
          }
        })
    }

    //查看是否有该orderid的售后订单
    wx.request({
      url: 'http://127.0.0.1:8080/afterService/selectAfterService',
      method:"POST",
      data:{orderid:options.orderid},
      success(res){
        // console.log(res.data)
        //存在订单则渲染并显示状态
        if(res.data != ""){
          var percent = res.data[0].serviceResult
          var i=0;
          while(percent[i] != '金'){
            i++;
          }
          var per = parseFloat(percent.substring(i+1,i+4))*0.01;
          var value = per*that.data.deposit
          var data = res.data[0];
          that.setData({
            showpic:true,
            judgetext:data.afterServiceText,
            picurls:JSON.parse(data.afterServicePic),
            isservice:true,
            finalresult:data.serviceResult,
            applymoney:value,
            applystate:data.serviceState
          })
        }else{
          wx.request({
          url: 'http://127.0.0.1:8080/order/orderById',
          method:"POST",
          data:{orderid:options.orderid},
          success(res){
            if(res.data != ""){
              var data = res.data[0];
              // console.log(data)
              var nowtime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
              var time = (Date.parse(nowtime) - Date.parse(data.deliveryTime))/1000/60/60/24;
              // console.log(time)
              if(time>=2 || time<=0){
                that.setData({
                  applystate:"距离归还物品日期超过两天(无法售后)"
                })
              }


            }
          
          }
        })
        }
      }
    })

//给onlyArray赋值
    var data = {
      customArray: this.data.customArray,
      customIndex: this.data.customIndex,
      onlyArray: this.data.onlyArray,
    };
    for (var i = 0; i < data.customArray.length; i++) {
      data.onlyArray[0].push(data.customArray[i].name);
    }
    for (var j = 0; j < data.customArray[data.customIndex[0]].dept.length; j++) {
      data.onlyArray[1].push(data.customArray[data.customIndex[0]].dept[j].name);
    }
    for (var k = 0; k < data.customArray[data.customIndex[0]].dept[data.customIndex[1]].product.length; k++) {
      data.onlyArray[2].push(data.customArray[data.customIndex[0]].dept[data.customIndex[1]].product[k].name);
    }
    this.setData(data);
  },

  // 获取商品评价
  getjudgetext(e){
    // console.log(e)
    this.setData({
      judgetext:e.detail.value
    })
  },

  // 添加商品快照
  addpic(e){
    let that = this;
    wx.chooseImage({
      count: 9,
      success(res){
        var picarray = that.data.picurls.concat(res.tempFilePaths)
        // console.log(picarray)
        that.setData({
          picurls:picarray,
          showpic:true
        })
      }
    })
  },
  //删除照片
  delpic(e){
    console.log(e)
    let that = this;
    var index = e.currentTarget.dataset.index;
    var del = this.data.picurls
    wx.showModal({
      content: '是否删除该照片',
      title: '提示',
      success(res){
        if(res.confirm){
          del.splice(index,1)
          var len = del.length
          if(len == 0){
            that.setData({
              showpic:false
            })
          }
          that.setData({
            picurls:del
          })
        }
      },
    })
    
  },
  // 查看图片
  showpic(e){
    var index  =e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.picurls[index],     //当前图片地址
      urls: this.data.picurls,                 //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  //多列自定义选择器改变value的方法
  choosecause(e){
    var customArray = this.data.customArray,
      customIndex = this.data.customIndex,
      onlyArray = this.data.onlyArray;

    console.log('picker发送选择改变，携带值为', e.detail.value);
    //此处e.detail.value为当前选择的列的下标值数组，如[0,1,0]
    
    console.log('picker最终选择值为：', onlyArray[0][customIndex[0]], onlyArray[1][customIndex[1]], onlyArray[2][customIndex[2]]);
    var index = onlyArray[2][customIndex[2]].indexOf("%");//获取第一个"_"的位置
    var percent = parseFloat(onlyArray[2][customIndex[2]].substring(2,index)) * 0.01;
    var value = parseFloat(this.data.deposit)*percent
    console.log(value)
    this.setData({
      customIndex: e.detail.value,
      applymoney:value.toFixed(2)
    })
  },

  //多列自创选择器换列方法
  changecol(e) {
    var customArray = this.data.customArray,
      customIndex = this.data.customIndex,
      onlyArray = this.data.onlyArray;

    customIndex[e.detail.column] = e.detail.value;
    // console.log(onlyArray);

    var searchColumn = () => {
      for (var i = 0; i < customArray.length; i++) {
        var arr1 = [];
        var arr2 = [];
        if (i == customIndex[0]) {
          for (var j = 0; j < customArray[i].dept.length; j++) {
            arr1.push(customArray[i].dept[j].name);
            if (j == customIndex[1]) {
              for (var k = 0; k < customArray[i].dept[j].product.length; k++) {
                arr2.push(customArray[i].dept[j].product[k].name);
              }
              onlyArray[2] = arr2;
            }
          }
          onlyArray[1] = arr1;
        }
      };
    }

    switch (e.detail.column) {
      case 0:
        customIndex[1] = 0;
        customIndex[2] = 0;
        searchColumn();
        break;
      case 1:
        customIndex[2] = 0;
        searchColumn();
        break;
    }
    this.setData({
      onlyArray: onlyArray,
      customIndex: customIndex
    });
  },

  //申请售后
  apply(){
    var that = this;
    wx.showModal({
      title: '确定提交',
      complete: (res) => {
        if(res.confirm){
          //上传完成后把文件上传到服务器
          var arr = []
          var h = this.data.picurls.length;
          var i =0;
          for (i = 0; i < h; i++) {
          //上传文件
          // console.log(i,h)
          wx.uploadFile({
            url: 'http://127.0.0.1:8080/image/upload',
            filePath: this.data.picurls[i],
            name: "file",
            header: {
                "content-type": "multipart/form-data"
            },
            success: function ({ data: res }) {
            // console.log(res)
            res = JSON.parse(res);
            const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
            // console.log(pic_url)
            // 图片路径集合
            arr.unshift(pic_url);
            },
            fail: function (err) {
              wx.showToast({
                title: "上传失败",
                icon: "error",
                duration: 2000
              })
            },
            complete: function (result) {
              // console.log(result.errMsg)
              }
            })
          }

          setTimeout(function(){
            var data = that.data;
            // console.log(data)
            var changeItemTime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);

            var newDateTime=new Date().getTime();

            var data1={
              afterserviceid:'s'+newDateTime,
              afterservicepic:JSON.stringify(arr),
              afterservicetext:data.judgetext,
              applicationtime:changeItemTime,
              serviceresult:data.onlyArray[0][data.customIndex[0]]+data.onlyArray[1][data.customIndex[1]]+data.onlyArray[2][data.customIndex[2]],
              orderidforservice:data.orderid,
              useridforservice:wx.getStorageSync('openid')
            }
            // console.log(data1)
            wx.request({
              url: 'http://127.0.0.1:8080/afterService/addAfterService',
              method:"POST",
              data:data1,
              success(res){
                // console.log(res)
                if(res.data){
                  wx.navigateBack({
                    delta: 2,
                    success: (res) => {
                      wx.showToast({
                        title: '申请已提交',
                        icon:"success"
                      })
                    },
                  })
                }
              }
            })


          },100)

        }
      }
    })
  }
 




})